package cn.fl.project.service.impl;

import cmm.comm.facade.framework.api.ISysDictionaryApiService;
import cmm.comm.facade.upload.api.IUploadApiService;
import cmm.comm.facade.upload.dto.SysUlFilesRecDTO;
import cmm.mid.core.framework.dto.DataResultDTO;
import cmm.mid.core.framework.page.DataResultVO;
import cmm.mid.core.framework.page.Pager;
import cn.cmm.base.framework.constant.BaseConstant;
import cn.cmm.base.framework.constant.BaseExceptionConstant;
import cn.cmm.base.framework.exception.BaseException;
import cn.cmm.base.framework.utils.BaseLogUtils;
import cn.cmm.base.framework.utils.CollectionUtils;
import cn.cmm.base.framework.utils.DecimalUtils;
import cn.cmm.base.framework.utils.StringUtils;
import cn.cmm.cache.framework.utils.PropertiesCacheUtils;
import cn.fl.framework.base.context.CurrentThreadContext;
import cn.fl.project.condition.PrjPrdPaySchDQueryCondition;
import cn.fl.project.constant.PrjBscInfoConstant;
import cn.fl.project.constant.PrjPrdPaySchDConstant;
import cn.fl.project.constant.PrjQuatPrpsConstant;
import cn.fl.project.constant.PrjQuatPrpsFeeConstant;
import cn.fl.project.dto.PrjPrdPaySchDDTO;
import cn.fl.project.service.IPrjBscInfoService;
import cn.fl.project.service.IPrjPrdPaySchDApiService;
import cn.fl.project.service.IPrjPrdPaySchDService;
import cn.fl.project.transform.PrjPrdPaySchDVOTransform;
import cn.fl.project.vo.PrjPrdPaySchDVO;
import cn.fl.project.vo.PrjPrdPaySchMVO;
import cn.fl.system.transform.SysUlFilesRecVOTransform;
import cn.fl.system.vo.SysUlFilesRecVO;
import cn.fl.upload.constant.UploadConstant;
import fl.flow.facade.flow.constant.FlowConstant;
import fl.flow.facade.flow.dto.FlowStartParamsDTO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
/**
 * @Description: 项目产品支付表主明细信息 客户端服务层接口实现
 * 业务层方法名称前缀：
 * 新增：add*
 * 删除：remove*
 * 修改：modify*
 * 批量：batch*
 * 查询对象：select* get*
 * 查询集合：search*
 */
@Service
public class PrjPrdPaySchDServiceImpl implements IPrjPrdPaySchDService {

	/**
	 * 日志
	 */
	@SuppressWarnings("unused")
	private static final Logger logger = LoggerFactory.getLogger(PrjPrdPaySchDServiceImpl.class);
	
	/**
	 * TODO 自定义 API 暴露服务
	 */
	@Autowired
	private IPrjPrdPaySchDApiService prjPrdPaySchDApiService;
	@Autowired
	private ISysDictionaryApiService sysDictionaryApiService;
	@Autowired
	private IPrjBscInfoService prjBscInfoService;
	
	/**
	 * TODO 自定义 API 暴露服务
	 */
	@Autowired
	private IUploadApiService uploadApiService;
	

	@Override
	public PrjPrdPaySchDVO selectById(Long id) throws BaseException{
		if(StringUtils.isEmpty(id)) return null;
		PrjPrdPaySchDDTO dto = this.prjPrdPaySchDApiService.selectPrjPrdPaySchDById(id);
		return PrjPrdPaySchDVOTransform.toVO(dto);
	}

	@Override
	public Long add(PrjPrdPaySchDVO entity) throws BaseException{
		if(null == entity) return null;
		return this.prjPrdPaySchDApiService.addPrjPrdPaySchD(PrjPrdPaySchDVOTransform.toDTO(entity));
	}

	@Override
	public boolean removeByIds(List<Long> ids) throws BaseException{
		if(CollectionUtils.isEmpty(ids)) return false;
		return this.prjPrdPaySchDApiService.removePrjPrdPaySchDByIds(ids,CurrentThreadContext.getCurrentUserId());
	}

	@Override
	public boolean modify(PrjPrdPaySchDVO entity) throws BaseException{
		if(null == entity) return false;
		return this.prjPrdPaySchDApiService.modifyPrjPrdPaySchD(PrjPrdPaySchDVOTransform.toDTO(entity));
	}

	@Override
	public Pager searchListPage(Pager page) throws BaseException{
		if(null == page) page = new Pager();
		page = this.prjPrdPaySchDApiService.searchPrjPrdPaySchDListPage(page,CurrentThreadContext.getCurrentSysCd(),CurrentThreadContext.getCurrentOrgCd());
		List<PrjPrdPaySchDVO> resultList = PrjPrdPaySchDVOTransform.toVOList((List<PrjPrdPaySchDDTO>)page.getResultList());
		if(CollectionUtils.isNotEmpty(resultList)){
				for (PrjPrdPaySchDVO prjPrdPaySchDVO : resultList) {
					prjPrdPaySchDVO.setFeeAmt(DecimalUtils.convertFenToYuan(prjPrdPaySchDVO.getFeeAmt().longValue()));
				}
				page.setResultList(resultList);
		}
		return page;
	}
	
	@Override
	public List<PrjPrdPaySchDVO> searchList(PrjPrdPaySchDQueryCondition condition) throws BaseException{
		 return PrjPrdPaySchDVOTransform.toVOList(this.prjPrdPaySchDApiService.searchPrjPrdPaySchDList(condition));
	}

	@Override
	public DataResultVO addPrjPrdPayRickDep(PrjPrdPaySchDVO detail) throws BaseException {
		DataResultVO resultVO = new  DataResultVO();
		if(null==detail){
			throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_600,"风险保证金参数不能为空！");
		}
		List<SysUlFilesRecDTO> fileList = new ArrayList<SysUlFilesRecDTO>();
		if(CollectionUtils.isNotEmpty(detail.getFileList())){
			List<SysUlFilesRecVO> fileVOList = detail.getFileList();
			for (SysUlFilesRecVO sysUlFilesRecVO : fileVOList) {
				sysUlFilesRecVO.setTabNm("PRJ_PRD_PAY_SCH_D");
				sysUlFilesRecVO.setIsDel(BaseConstant.IS_YESNO_NO);
				sysUlFilesRecVO.setOrgCd(PrjBscInfoConstant.CODE_PRJ_FILE_DEF_ORG);
				sysUlFilesRecVO.setAbsLocPath(PropertiesCacheUtils.getProperty(UploadConstant.UPLOAD_ROOT_PATH)+sysUlFilesRecVO.getFilePath());

				sysUlFilesRecVO.setSysCd(CurrentThreadContext.getCurrentSysCd());
				sysUlFilesRecVO.setCfgCd(PrjPrdPaySchDConstant.PRJ_PRD_Pay_SCH_D_FILE_CODE);
				sysUlFilesRecVO.setCfgDtlCd(PrjPrdPaySchDConstant.PRJ_PRD_Pay_SCH_D_FILE_DETAIL_CODE);
				fileList.add(SysUlFilesRecVOTransform.toDTO(sysUlFilesRecVO));
			}
		}
		PrjPrdPaySchDDTO dto = PrjPrdPaySchDVOTransform.toDTO(detail);
		if(CollectionUtils.isNotEmpty(fileList)){
			dto.setFileList(fileList);
		}
		FlowStartParamsDTO flowStartParamsDTO = this.getFlowStartParams(FlowConstant.FLOW_BUSINESS_TYP_RISK,FlowConstant.FLOW_MODEL_TYP_RISK);
		dto.setFlowStartParamsDTO(flowStartParamsDTO);
		DataResultDTO resultdto = 	 this.prjPrdPaySchDApiService.addPrjPrdPayRickDep(dto);
	
		resultVO.setData(resultdto.getData());
		resultVO.setInfo(resultdto.getInfo());
		return resultVO;
	}

	@Override
	public Long removeSettFeeList(Long paySchId, List<Long> idsList) throws BaseException{
		return prjPrdPaySchDApiService.removeSettFeeList(paySchId, idsList, CurrentThreadContext.getCurrentUserId());
	}

	@Override
	public Long addSettFeeList(List<PrjPrdPaySchDVO> feeList,Long setAmt,Long paySchId) {
		return this.prjPrdPaySchDApiService.addSettFeeList(PrjPrdPaySchDVOTransform.toDTOList(feeList),setAmt,paySchId);
	}

    @Override
    public boolean addOrRemoveSettFeeList(Long paySchId, List<PrjPrdPaySchDDTO> changeList) throws BaseException {
        return prjPrdPaySchDApiService.addOrRemoveSettFeeList(paySchId, changeList);
    }

    @Override
	public Pager searchSettFeeListPage(Pager page) throws BaseException {
		Pager pager =	this.searchListPage(page);
		List<PrjPrdPaySchDVO> resultList = (List<PrjPrdPaySchDVO>)pager.getResultList();
		if(CollectionUtils.isNotEmpty(resultList)){
			List<PrjPrdPaySchDVO> list = new ArrayList<PrjPrdPaySchDVO>();
				for (int i=0;i<resultList.size();i++) {
					PrjPrdPaySchDVO prjPrdPaySchDVO = resultList.get(i);
					if (!(null != prjPrdPaySchDVO.getIsSysDef()
							&& prjPrdPaySchDVO.getIsSysDef().equals(BaseConstant.IS_YESNO_YES)
							&& (prjPrdPaySchDVO.getFeeTypCd().equals(PrjQuatPrpsFeeConstant.FEE_TYP_CD_201)
							|| prjPrdPaySchDVO.getFeeTypCd().equals(PrjQuatPrpsFeeConstant.FEE_TYP_CD_103)
							|| prjPrdPaySchDVO.getFeeTypCd().equals(PrjQuatPrpsFeeConstant.FEE_TYP_CD_207)))) {
						if (!prjPrdPaySchDVO.getFeeTypCd().equals(PrjQuatPrpsFeeConstant.FEE_TYP_CD_104)) {
							list.add(prjPrdPaySchDVO);
						}
					}
				}
				pager.setResultList(list);
		}
		/*if(CollectionUtils.isEmpty(pager.getResultList())){
		PrjPrdPaySchDQueryCondition pageQc = (PrjPrdPaySchDQueryCondition)page.getCondition();
		//费用对应关系
		List<SysDictionaryDTO>  allList =   this.sysDictionaryApiService.searchGroup(CurrentThreadContext.getCurrentSysCd(), CurrentThreadContext.getCurrentOrgCd(), DictionaryConstant.CODE_PRJ_QUAT_FEE_ALL_TYP_CD);//所有费用类型
		List<SysDictionaryDTO> settList =  this.sysDictionaryApiService.searchGroup(CurrentThreadContext.getCurrentSysCd(), CurrentThreadContext.getCurrentOrgCd(), DictionaryConstant.CODE_PRJ_QUAT_FEE_SETT_TYP_CD);//结清类型
		Map<String,String> settMap =  this.sysDictionaryApiService.searchGroupToMap(CurrentThreadContext.getCurrentSysCd(), CurrentThreadContext.getCurrentOrgCd(), DictionaryConstant.CODE_PRJ_QUAT_FEE_SETT_TYP_CD);//结清类型
		List<PrjPrdPaySchDVO> subFeeAmtDetilList = new ArrayList<PrjPrdPaySchDVO>();
		PrjPrdPaySchDQueryCondition qc = new PrjPrdPaySchDQueryCondition();
		qc.setFeeClsCd(PrjQuatPrpsConstant.CODE_PRJ_QUAT_FEE_CLS_TYP_PRPS);
		qc.setPaySchId(pageQc.getPaySchId());
		qc.setPayPd(Long.valueOf(PrjQuatPrpsConstant.CODE_PRJ_PRD_PAY_PD));
		List<PrjPrdPaySchDVO> feeDetail = this.searchList(qc);
		for (SysDictionaryDTO sett : settList) {
			for (SysDictionaryDTO all : allList) {
				if(null!=all.getCodeAttr2()){
					//结清的费用项对应方案的费用项
					if(sett.getCode().equals(all.getCodeAttr2())){
						//获取方案费用类型
						String feeTypCd = all.getCode();
						PrjPrdPaySchDDTO total = new PrjPrdPaySchDDTO();
						total.setFeeTypCd(all.getCodeAttr2());
						if(settMap.containsKey(all.getCodeAttr2())){
							total.setFeeTypCdNm(settMap.get(all.getCodeAttr2()));
						}
						total.setCapFlow(PrjQuatPrpsConstant.CODE_PRJ_QUAT_CASH_FLOW_OUT);
						//获取方案中的费用项信息
						for (PrjPrdPaySchDVO prjPrdPaySchDDTO : feeDetail) {
							if(prjPrdPaySchDDTO.getFeeTypCd().equals(feeTypCd)){
								prjPrdPaySchDDTO.setFeeTypCd(all.getCodeAttr2());
								prjPrdPaySchDDTO.setId(null);
								prjPrdPaySchDDTO.setFeeAmt(DecimalUtils.convertFenToYuan(prjPrdPaySchDDTO.getFeeAmt().longValue()));
								if(settMap.containsKey(all.getCodeAttr2())){
									prjPrdPaySchDDTO.setFeeTypCdNm(settMap.get(all.getCodeAttr2()));
								}
								prjPrdPaySchDDTO.setIsSysDef(BaseConstant.IS_YESNO_YES);
								subFeeAmtDetilList.add(prjPrdPaySchDDTO);
							}
						}
					}
				}
			}
		}
		if(CollectionUtils.isNotEmpty(subFeeAmtDetilList)){
			for (PrjPrdPaySchDVO sett : subFeeAmtDetilList) {
				for (SysDictionaryDTO all : allList) {
					if(sett.getFeeTypCd().equals(all.getCode())){
						if(all.getCodeAttr1().equals(PrjQuatPrpsConstant.CODE_PRJ_QUAT_CASH_FLOW_OUT)){
							sett.setCapFlow(PrjQuatPrpsConstant.CODE_PRJ_QUAT_CASH_FLOW_OUT);
						}
						if(all.getCodeAttr1().equals(PrjQuatPrpsConstant.CODE_PRJ_QUAT_CASH_FLOW_IN)){
							sett.setCapFlow(PrjQuatPrpsConstant.CODE_PRJ_QUAT_CASH_FLOW_IN);
						}
					}
				}
			}
		}
		
		List<PrjPrdPaySchDVO> resultList = new ArrayList();
			resultList.addAll(subFeeAmtDetilList);
			pager.setResultList(resultList);
		}*/	
		return pager;
	}
	    
	/******************************************************
     * 获取发起流程对象-添加风险保证金
     * @param businessType:业务类型(FlowConstant.FLOW_BUSINESS_TYP_RISK)
     * @param modelTyp:流程业务分类:FlowConstant.FLOW_MODEL_TYP_RISK
     * @return
     * @throws BaseException
     *****************************************************/
    private FlowStartParamsDTO getFlowStartParams(String businessType,String modelTyp)throws BaseException{
    	if(StringUtils.isEmpty(modelTyp)){
    		throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_600, "流程业务分类不能为空");
    	}
        FlowStartParamsDTO flowStartParamsDTO = new FlowStartParamsDTO();
        //流程定义KEY和流程定义ID不定义  流程发起的时候会根据模块类型查找唯一流程去发起
        //flowStartParamsDTO.setProcDefKey("");
        //flowStartParamsDTO.setProcDefId("");
        flowStartParamsDTO.setAudStsCd(FlowConstant.FLOW_CHECK_STATE_IN);
        flowStartParamsDTO.setWordsInTheTable(PrjBscInfoConstant.PRJ_FLOW_S_H_PRJ);
        flowStartParamsDTO.setCrtUsrId(CurrentThreadContext.getCurrentUserId());
        flowStartParamsDTO.setOrgCd(CurrentThreadContext.getCurrentOrgCd());
        flowStartParamsDTO.setSysCd(CurrentThreadContext.getCurrentSysCd());
        flowStartParamsDTO.setBuOrgCd(CurrentThreadContext.getCurrentBuOrgCd());
        flowStartParamsDTO.setInitiator(String.valueOf(CurrentThreadContext.getCurrentUserId()));
        flowStartParamsDTO.setInitiatorNm(CurrentThreadContext.getCurrentUserName());
        flowStartParamsDTO.setProcPriority(FlowConstant.FLOW_PRIORITY_EMERGENCY);//优先级,可以在界面定义
        flowStartParamsDTO.setBusinessType(businessType);//TODO 确认用不用
        flowStartParamsDTO.setModelTyp(modelTyp);//需要和流程配置中的模块类型匹配
        return flowStartParamsDTO;
    }

	@Override
	public List<PrjPrdPaySchDVO> selectPaySchByDelStatusAndPaySchId(Long paySchId, Integer flowDelStatus)
			throws BaseException {
		
		return PrjPrdPaySchDVOTransform.toVOList(this.prjPrdPaySchDApiService.selectPaySchByDelStatusAndPaySchId(paySchId,flowDelStatus));
	}

	@Override
	public List<PrjPrdPaySchDVO> searchListByPayPd(
			PrjPrdPaySchDQueryCondition condition) throws BaseException {
		return PrjPrdPaySchDVOTransform.toVOList(this.prjPrdPaySchDApiService.searchListByPayPd(condition));
	}

	@Override
	public Long searchCurrLnkCompCrAmtByLnkId(Long compId) throws BaseException {
		if(null==compId) return null;
		return prjPrdPaySchDApiService.searchCurrLnkCompCrAmtByLnkId(compId);
	}
	

	@Override
	public void modifySettAmt(Long setAmt, Long payId) throws BaseException {
		prjPrdPaySchDApiService.modifySettAmt(setAmt,payId);
	}

	@Override
	public void addSettFeeList(List<PrjPrdPaySchDVO> feeList) throws BaseException {
		prjPrdPaySchDApiService.addSettFeeList(PrjPrdPaySchDVOTransform.toDTOList(feeList));
	}
	/**
	 * 获取借款未核销金额合计
	 * @param pay
	 */
	@Override
	public void computeLoanArAmt(PrjPrdPaySchMVO pay, String paySchId){
		try{
			//借款相关 start
			PrjPrdPaySchDQueryCondition qc = new PrjPrdPaySchDQueryCondition();
			qc.setFeeClsCd(PrjQuatPrpsConstant.CODE_FIN_CLS_TYP_SETT);
			qc.setPayPd(Long.valueOf(PrjQuatPrpsConstant.CODE_PRJ_PRD_FEE_PD));//期次为0为费用项
			if(StringUtils.isNotBlank(paySchId)){
				qc.setPaySchId(Long.valueOf(paySchId));
			}
			Pager page = new Pager();
			page.setCondition(qc);
			//Pager pager = prjPrdPaySchDService.searchListPage(page);//查询借款相关的费用项
			Pager pager = this.searchListPage(page);//查询借款相关的费用项
			if(CollectionUtils.isNotEmpty(pager.getResultList())){
				List<PrjPrdPaySchDVO> prjPrdPaySchDVOList = (List<PrjPrdPaySchDVO>)pager.getResultList();
				Long finArAmtSum = 0L;
				Double finArAmtDSum = 0d;
				if(CollectionUtils.isNotEmpty(prjPrdPaySchDVOList)){
					for(PrjPrdPaySchDVO p : prjPrdPaySchDVOList){
						if(StringUtils.isNotEmpty(p.getArAmt())){
							finArAmtSum += p.getArAmt();
						}
					}
					finArAmtDSum = DecimalUtils.convertFenToYuan(finArAmtSum);
				}
				if(null != pay){
					if(null != pay.getFinalPayAmt()){
						pay.setFinalPayAmt(pay.getFinalPayAmt() + finArAmtDSum);
					}else{
						pay.setFinalPayAmt(finArAmtDSum);
					}

					if(null != pay.getTotalSettAmt()){
						pay.setTotalSettAmt(pay.getTotalSettAmt() + finArAmtDSum);
					}else{
						pay.setTotalSettAmt(finArAmtDSum);
					}
				}
			}
			//借款相关 end
		}catch (Exception e){
			BaseLogUtils.info(logger, "computeLoanArAmt", "获取借款未核销金额合计:" + ".ERROR:" + e.getMessage(), CurrentThreadContext.getCurrentUserName());
		}
	}
}
